import os

from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtCore import pyqtSignal, Qt, QEasingCurve
from PyQt6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import CheckBox, DropDownPushButton, LineEdit, PushButton, SpinBox, ElevatedCardWidget, ImageLabel, \
	CaptionLabel, FlowLayout, ScrollArea, RoundMenu, Action, ComboBox
from qfluentwidgets import FluentIcon as FIF
from src.component.RunChartMessageBox import ChartMessageBox


class InspectionInterface(QWidget):
	def __init__(self,text :str, control,parent=None):
		super().__init__(parent=parent)
		self.control = control
		self.ui = Ui_Form(control)
		self.ui.setupUi(self)
		self.setStyleSheet("background: transparent;")
		self.setObjectName(text.replace(' ', '-'))

#孔位卡片
class IndexCard(ElevatedCardWidget):
	indexCardClicked = pyqtSignal(object)  # 自定义信号，准备发送自己的信息
	def __init__(self, index, parent=None):  #传入自己的编号:int
		super().__init__(parent)
		self.parent = parent
		self.index = index
		self.is_can_clicked = True#之后改为false
		iconPath = "./resources/image/file_logo.png"#之后拼接改为数字的png
		self.iconWidget = ImageLabel(iconPath, self)
		self.label = CaptionLabel(str(self.index), self)

		self.iconWidget.scaledToHeight(30)

		self.vBoxLayout = QVBoxLayout(self)
		self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
		self.vBoxLayout.addStretch(1)
		self.vBoxLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignCenter)
		self.vBoxLayout.addStretch(1)
		self.vBoxLayout.addWidget(self.label, 0, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom)

		self.setFixedSize(84, 88)

		self.clicked.connect(self.emit_indexcard_clicked)

	def emit_indexcard_clicked(self):
		print(f"当前孔位编号为{self.index},当前可点击状态{str(self.is_can_clicked)}")
		#self.indexCardClicked.emit(self.index)
		#如果为可点击状态，则弹出对应的表格界面
		if(self.is_can_clicked):
			try:
				print(f"打开孔位{self.index}的temp文件")
				chart_message_box = ChartMessageBox(self.index,self.parent)  # 暂时传入文件名
				chart_message_box.exec()
			except:
				print("打开失败，大概率是选择错误,之后用warn报错")


class index_option_panel(ScrollArea):
	def __init__(self,parent=None):
		super().__init__(parent=parent)
		self.setStyleSheet("QScrollArea { border: none; }")
		self.layout = FlowLayout(self, needAni=True)
		self.layout.setAnimation(250, QEasingCurve.Type.OutQuad)

		self.layout.setContentsMargins(30, 30, 30, 30)
		self.layout.setVerticalSpacing(20)
		self.layout.setHorizontalSpacing(10)

		for i in range(16):
			checkBox = CheckBox(f"位置{i}",self)
			checkBox.setTristate(False)
			self.layout.addWidget(checkBox)
			self.setMinimumSize(500, 100)
			self.setMaximumSize(12000, 600)

	def get_selected_options(self):
		selected_numbers = []
		for i in range(self.layout.count()):
			item = self.layout.itemAt(i)
			if isinstance(item.widget(), CheckBox) and item.widget().isChecked():
				option_number = int(item.widget().text().replace("位置", ""))
				selected_numbers.append(option_number)
		return selected_numbers

	def fn_empty(self):
		print("清空全部")
		for i in range(self.layout.count()):
			widget = self.layout.itemAt(i).widget()
			if isinstance(widget, CheckBox):
				widget.setChecked(False)

	def fn_select_all(self):
		print("全选")
		for i in range(self.layout.count()):
			widget = self.layout.itemAt(i).widget()
			if isinstance(widget, CheckBox):
				widget.setChecked(True)

class CardPanel(ScrollArea):
	def __init__(self,parent=None):
		super().__init__(parent=parent)
		self.parent = parent
		self.setStyleSheet("QScrollArea { border: none; }")
		self.layout = FlowLayout(self, needAni=True)
		self.layout.setAnimation(250, QEasingCurve.Type.OutQuad)

		self.layout.setContentsMargins(30, 30, 30, 30)
		self.layout.setVerticalSpacing(20)
		self.layout.setHorizontalSpacing(10)

		for i in range(16):
			indexCard = IndexCard(i,self.parent)
			self.layout.addWidget(indexCard)

		#self.update_indexCard(8)

		self.setMinimumSize(500,500)
		self.setMaximumSize(12000,800)
		#self.setStyleSheet('background: red;')

	#清空所有的卡片,暂时报错，暂停使用，写死
	def clear_indexCard(self):
		for i in (self.layout._items):
			self.layout.removeItem(i)
		# for i in(range(self.layout.count())):
		# 	item = self.layout.itemAt(i)
		# 	if item.widget():
		# 		item.widget().deleteLater()

	#更新所有卡片，num为新生成的卡片数量
	def update_indexCard(self,num:int):
		# 清空所有卡片
		#self.clear_indexCard()
		# 添加新的卡片
		for i in range(num):
			indexCard = IndexCard(i,self.parent)
			self.layout.addWidget(indexCard)
		# 重新布局
		self.layout.update()



class Ui_Form(object):
	platform_ver_cliecked = pyqtSignal(object) #轮盘型号更改使用的自定义信号
	def __init__(self,control):
		self.control = control
	def setupUi(self, Form):
		Form.setObjectName("Form")
		Form.resize(734, 489)
		Form.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
		Form.setAutoFillBackground(True)
		self.gridLayout = QtWidgets.QGridLayout(Form)
		self.gridLayout.setObjectName("gridLayout")
		# self.frame_2 = QtWidgets.QFrame(parent=Form)
		# self.frame_2.setFrameShape(QtWidgets.QFrame.Shape.StyledPanel)
		# self.frame_2.setFrameShadow(QtWidgets.QFrame.Shadow.Raised)
		# self.frame_2.setObjectName("frame_2")
		# # self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_2)
		# # self.horizontalLayout_2.setObjectName("horizontalLayout_2")
		# # self.CheckBox_2 = CheckBox(parent=self.frame_2)
		# # self.CheckBox_2.setObjectName("CheckBox_2")
		# # self.horizontalLayout_2.addWidget(self.CheckBox_2)
		# self.gridLayout.addWidget(self.frame_2, 1, 1, 5, 3)
		self.formLayout = QtWidgets.QFormLayout()
		self.formLayout.setLabelAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
		self.formLayout.setFormAlignment(QtCore.Qt.AlignmentFlag.AlignRight|QtCore.Qt.AlignmentFlag.AlignTop|QtCore.Qt.AlignmentFlag.AlignTrailing)
		self.formLayout.setContentsMargins(-1, 20, 20, -1)
		self.formLayout.setObjectName("formLayout")
		self.label = QtWidgets.QLabel(parent=Form)
		self.label.setObjectName("label")
		self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label)
		self.comboBox = ComboBox(parent=Form)
		#self.comboBox.setMaximumSize(QtCore.QSize(200, 16777215))
		self.comboBox.setObjectName("comboBox")
		self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.FieldRole, self.comboBox)
		self.label_5 = QtWidgets.QLabel(parent=Form)
		self.label_5.setObjectName("label_5")
		self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_5)
		self.LineEdit_3 = LineEdit(parent=Form)
		#self.LineEdit_3.setMaximumSize(QtCore.QSize(200, 33))
		self.LineEdit_3.setObjectName("LineEdit_3")
		self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.FieldRole, self.LineEdit_3)
		self.label_2 = QtWidgets.QLabel(parent=Form)
		self.label_2.setObjectName("label_2")
		self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_2)
		self.LineEdit = LineEdit(parent=Form)
		#self.LineEdit.setMaximumSize(QtCore.QSize(200, 33))
		self.LineEdit.setText("")
		self.LineEdit.setObjectName("LineEdit")
		self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.FieldRole, self.LineEdit)
		self.label_3 = QtWidgets.QLabel(parent=Form)
		self.label_3.setObjectName("label_3")
		self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_3)
		self.LineEdit_2 = LineEdit(parent=Form)
		#self.LineEdit_2.setMaximumSize(QtCore.QSize(200, 33))
		self.LineEdit_2.setObjectName("LineEdit_2")
		self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.FieldRole, self.LineEdit_2)
		self.label_4 = QtWidgets.QLabel(parent=Form)
		self.label_4.setObjectName("label_4")
		self.formLayout.setWidget(5, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_4)
		self.SpinBox = SpinBox(parent=Form)
		#self.SpinBox.setMaximumSize(QtCore.QSize(200, 33))
		self.SpinBox.setObjectName("SpinBox")
		self.formLayout.setWidget(5, QtWidgets.QFormLayout.ItemRole.FieldRole, self.SpinBox)

		self.data_folder_name_label = QtWidgets.QLabel(parent=Form)
		self.data_folder_name_label.setObjectName("data_folder_name_label")
		self.formLayout.setWidget(6, QtWidgets.QFormLayout.ItemRole.LabelRole, self.data_folder_name_label)
		self.data_folder_name_LineEdit = LineEdit(parent=Form)
		# self.LineEdit.setMaximumSize(QtCore.QSize(200, 33))
		self.data_folder_name_LineEdit.setText("")
		self.data_folder_name_LineEdit.setObjectName("data_folder_name_LineEdit")
		self.formLayout.setWidget(6, QtWidgets.QFormLayout.ItemRole.FieldRole, self.data_folder_name_LineEdit)

		self.gridLayout.addLayout(self.formLayout, 1, 4, 2, 2)#设置数据的地方
		self.frame_3 = QtWidgets.QFrame(parent=Form)
		self.frame_3.setFrameShape(QtWidgets.QFrame.Shape.StyledPanel)
		self.frame_3.setFrameShadow(QtWidgets.QFrame.Shadow.Raised)
		self.frame_3.setObjectName("frame_3")
		self.verticalLayout = QtWidgets.QVBoxLayout(self.frame_3)
		self.verticalLayout.setObjectName("verticalLayout")
		self.horizontalLayout = QtWidgets.QHBoxLayout()
		self.horizontalLayout.setObjectName("horizontalLayout")
		spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum)
		self.horizontalLayout.addItem(spacerItem)

		self.look_background_button = PushButton(parent=self.frame_3)
		self.look_background_button.setObjectName("look_background_button")
		self.horizontalLayout.addWidget(self.look_background_button)

		self.get_background_button = PushButton(parent=self.frame_3)
		self.get_background_button.setObjectName("get_background_button")
		self.horizontalLayout.addWidget(self.get_background_button)

		self.del_background_button = PushButton(parent=self.frame_3)
		self.del_background_button.setObjectName("del_background_button")
		self.horizontalLayout.addWidget(self.del_background_button)

		self.PushButton_3 = PushButton(parent=self.frame_3)
		self.PushButton_3.setMaximumSize(QtCore.QSize(70, 33))
		self.PushButton_3.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
		self.PushButton_3.setObjectName("PushButton_3")
		self.horizontalLayout.addWidget(self.PushButton_3)
		self.PushButton_2 = PushButton(parent=self.frame_3)
		self.PushButton_2.setMaximumSize(QtCore.QSize(70, 33))
		self.PushButton_2.setObjectName("PushButton_2")
		self.horizontalLayout.addWidget(self.PushButton_2)
		self.PushButton = PushButton(parent=self.frame_3)
		self.PushButton.setMinimumSize(QtCore.QSize(150, 33))
		self.PushButton.setMaximumSize(QtCore.QSize(150, 33))

		font = QtGui.QFont()
		font.setFamily("Segoe UI")
		font.setPointSize(-1)
		font.setBold(True)
		self.PushButton.setFont(font)
		self.PushButton.setObjectName("PushButton")
		self.horizontalLayout.addWidget(self.PushButton)
		self.verticalLayout.addLayout(self.horizontalLayout)
		self.gridLayout.addWidget(self.frame_3, 5, 4, 1, 2)#启动清空的那三个按钮面板

		self.frame = QtWidgets.QFrame(parent=Form)
		self.frame.setFrameShape(QtWidgets.QFrame.Shape.StyledPanel)
		self.frame.setFrameShadow(QtWidgets.QFrame.Shadow.Raised)
		self.frame.setObjectName("frame")
		self.formLayout_2 = QtWidgets.QFormLayout(self.frame)
		self.formLayout_2.setObjectName("formLayout_2")
		#加入卡片面
		self.card_panel = CardPanel(parent=Form)
		self.formLayout_2.addWidget(self.card_panel)
		self.gridLayout.addWidget(self.frame, 1, 1, 5, 3)#左边卡片面板

		self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame)
		self.verticalLayout_2.setObjectName("verticalLayout_2")
		#加入位置选择面板
		self.index_option_panel = index_option_panel()
		self.verticalLayout_2.addWidget(self.index_option_panel)
		self.gridLayout.addLayout(self.verticalLayout_2, 3, 4, 2, 2)#选择孔位的面板
		# spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding,
		#                                     QtWidgets.QSizePolicy.Policy.Minimum)
		# self.gridLayout.addItem(spacerItem2, 1, 1, 2, 1)

		self.retranslateUi(Form)
		self.defaultSetting()
		self.signal_con()
		QtCore.QMetaObject.connectSlotsByName(Form)


	def retranslateUi(self, Form):
		_translate = QtCore.QCoreApplication.translate
		Form.setWindowTitle(_translate("Form", "Form"))
		# self.CheckBox_2.setText(_translate("Form", "Check box"))
		self.label.setText(_translate("Form", "轮盘型号"))
		self.comboBox.setPlaceholderText("选择轮盘型号")
		self.label_5.setText(_translate("Form", "中心波长（nm）"))
		self.label_2.setText(_translate("Form", "功率（nw）"))
		self.label_3.setText(_translate("Form", "积分时间"))
		self.label_4.setText(_translate("Form", "平均次数"))
		self.data_folder_name_label.setText(_translate("Form", "项目名称"))
		self.PushButton_3.setText(_translate("Form", "全选"))
		self.PushButton_2.setText(_translate("Form", "清空"))
		self.PushButton.setText(_translate("Form", "运行"))
		self.get_background_button.setText(_translate("Form", "获取背景"))
		self.del_background_button.setText(_translate("Form", "删除背景"))
		self.look_background_button.setText(_translate("Form", "查看背景"))
		#self.CheckBox.setText(_translate("Form", "轮盘图片和可操作的按钮"))

	def signal_con(self):
		self.comboBox.currentIndexChanged.connect(self.platform_ver_update)
		self.PushButton.clicked.connect(self.run_clicked)
		self.PushButton_2.clicked.connect(self.index_option_panel.fn_empty)
		self.PushButton_3.clicked.connect(self.index_option_panel.fn_select_all)
		self.look_background_button.clicked.connect(self.look_background)
		self.get_background_button.clicked.connect(self.get_save_background)
		self.del_background_button.clicked.connect(self.control.delete_background)



	def defaultSetting(self):
		items = ["S_16 v1.0","S_16 v2.0"]
		self.comboBox.addItems(items)
		self.comboBox.setCurrentIndex(-1)
		# self.DropDownPushButton.setMenu(self.platform_ver_menu)

		self.LineEdit_3.setText("830")
		self.LineEdit.setText("100")
		self.LineEdit_2.setText("1000")
		self.SpinBox.setValue(3)
		self.data_folder_name_LineEdit.setText("lastest")
		print(self)

	def slot_get_data_folder_name(self):
		return self.data_folder_name_LineEdit.text()

	# 发送自定义信号
	def platform_ver_update(self):
		whole_count = 16
		if self.comboBox.currentText() == "S_16 v1.0":
			whole_count = 16
		# if self.DropDownPushButton.text == "S_12 v1.0":
		# 	whole_count = 12
		print(f"更新为{whole_count}孔位")
		#self.card_panel.update_indexCard(whole_count)
		#self.platform_ver_cliecked.emit(whole_count)

	def get_save_background(self):
		integration_time = int(self.LineEdit_2.text())
		average_times = self.SpinBox.value()
		self.control.get_save_background(integration_time, average_times)

	def look_background(self):
		if os.path.exists('data/background/background.csv'):
			current_dir = os.path.dirname(os.path.abspath(__file__))
			folder = os.path.join(current_dir, '../../data/background/')
			folder = folder.replace(r'/', '\\')
			os.system("explorer.exe %s" % folder)
		else:
			print("背景文件不存在")



	def run_clicked(self):
		whole_count = 16
		center_wavelength = 830
		power = 100
		integration_time = 1000
		average_times = 3
		if self.comboBox.currentText() == "S_16 v1.0":
			whole_count = 16
		center_wavelength = int(self.LineEdit_3.text())
		power = int(self.LineEdit.text())
		integration_time = int(self.LineEdit_2.text())
		average_times = self.SpinBox.value()
		#获取被选中的选择框，把对应的数字放入list队列
		selected_options = self.index_option_panel.get_selected_options()
		print(f"开始运行，参数数据：孔洞数量 {whole_count}, 中心波长 {center_wavelength}, 功率 {power}, "
		      f"积分时间 {integration_time}, 平均次数 {average_times}, 项目名称 {self.data_folder_name_LineEdit.text()}")
		print(f"被选中的位置：{selected_options}")
		try:
			self.control.run(selected_options,power, integration_time, average_times,self.data_folder_name_LineEdit.text())
		except:
			print("运行失败，请检查设备连接")
